using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Configuration;
using System.Globalization;
using System.Collections;
using System.Data.SqlTypes;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace CodeUtils
{
    public enum DateFormat
    {
        MMDDYYYY,
        DDMMYYYY
    }

    public class BusinessUtility
    {

        #region CONSTATNTS
        public const string strActive = "ACTIVE";
        public const string strInActive = "INACTIVE";
        #endregion

        #region TO CHECK WHEATHER AN OBJECT IS AN INTEGER OR NOT

        public static bool IsInteger(object obj)
        {
            int i = 0;
            try
            {
                i = int.Parse(obj.ToString());
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static bool IsLong(object obj)
        {
            long i = 0;
            try
            {
                i = Convert.ToInt64(obj);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static bool IsNumeric(object obj)
        {
            bool check = true;
            string strNumeric = obj.ToString();
            foreach (char c in strNumeric)
            {
                if (!Char.IsDigit(c))
                {
                    check = false;
                }
            }
            return check;
        }

        #endregion

        #region TO CHECK WHEATHER AN OBJECT IS AN DECIMAL OR NOT

        public static bool IsDecimal(object obj)
        {
            decimal i = 0;
            try
            {
                i = decimal.Parse(obj.ToString());
            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        #region TO CHECK WHEATHER AN OBJECT IS AN DOUBLE OR NOT

        public static bool IsDouble(object obj)
        {
            double i = 0;
            try
            {
                i = double.Parse(obj.ToString());
            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        /// <summary>
        /// Converts to decimal.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static decimal ConvertToDecimal(object value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            if (value is decimal)
                return (decimal)value;
            else
                return ConvertToDecimal(value.ToString());
        }

        public static bool Match(IPAddress target, IPAddress mask)
        {
            if (target == null)
                throw new ArgumentNullException("target");
            if (mask == null)
                throw new ArgumentNullException("mask");

            byte[] targetBytes = target.GetAddressBytes();
            byte[] maskBytes = mask.GetAddressBytes();

            if (targetBytes.Length != maskBytes.Length)
                return false;

            for (int i = 0; i < targetBytes.Length; i++)
            {
                if (targetBytes[i] != maskBytes[i] && maskBytes[i] != 0)
                    return false;
            }

            return true;
        }

        /// <summary>
        /// Change Decimal To Ruppes
        /// </summary>
        /// <param name="decValue"></param>
        /// <param name="isChangeRequired">if we do not want this function to perform operation do this by setting isChangeRequest to false inside the fuction</param>
        /// <returns></returns>
        public static string ConvertDecimalToIndianRupees(double decValue, bool isChangeRequired)
        {
            string retValue = decValue.ToString();
            if (isChangeRequired)
            {
                retValue = "";
                string beforeDecimal = decValue.ToString();
                string afterDecimal = "";
                if (beforeDecimal.Contains("."))
                {
                    string[] decimalBreak = beforeDecimal.Split(new char[] { '.' });
                    beforeDecimal = decimalBreak[0];
                    afterDecimal = "." + decimalBreak[1];
                }

                if (beforeDecimal.Length > 3)
                {
                    char[] allChars = beforeDecimal.ToCharArray();

                    int totalCharCount = allChars.Length;

                    for (int index = totalCharCount - 1; index >= 0; index--)
                    {
                        if ((totalCharCount - index - 1) == 2)
                        {
                            retValue = "," + allChars[index].ToString() + retValue;
                        }
                        else if (((totalCharCount - index - 1) > 2) && ((totalCharCount - index - 1) % 2 == 0) && (index > 0))
                        {
                            retValue = "," + allChars[index].ToString() + retValue;
                        }
                        else
                        {
                            retValue = allChars[index].ToString() + retValue;
                        }
                    }
                }
                retValue += afterDecimal;
            }

            return retValue;
        }

        public static string ConvertStringToIndianRupees(string decValue, bool isChangeRequired)
        {
            string retValue = decValue;
            if (isChangeRequired)
            {
                retValue = "";
                string beforeDecimal = decValue;
                string afterDecimal = "";
                if (beforeDecimal.Contains("."))
                {
                    string[] decimalBreak = beforeDecimal.Split(new char[] { '.' });
                    beforeDecimal = decimalBreak[0];
                    afterDecimal = "." + decimalBreak[1];
                }

                if (beforeDecimal.Length > 3)
                {
                    char[] allChars = beforeDecimal.ToCharArray();

                    int totalCharCount = allChars.Length;

                    for (int index = totalCharCount - 1; index >= 0; index--)
                    {
                        if ((totalCharCount - index - 1) == 2)
                        {
                            retValue = "," + allChars[index].ToString() + retValue;
                        }
                        else if (((totalCharCount - index - 1) > 2) && ((totalCharCount - index - 1) % 2 == 0) && (index > 0))
                        {
                            retValue = "," + allChars[index].ToString() + retValue;
                        }
                        else
                        {
                            retValue = allChars[index].ToString() + retValue;
                        }
                    }
                }
                retValue += afterDecimal;
            }

            return retValue;
        }

        #region FUNCTIONS TO MANUPLATE DATE TIME

        public static bool IsValidDate(string strDate)
        {
            try
            {
                DateTime.ParseExact(strDate, "dd/mm/yyyy", null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static DateTime FormatDate(string formatString)
        {
            string strDateTime = formatString.Trim();
            string[] tempStr = strDateTime.Split('-');
            DateTime formatedDate = DateTime.MinValue;
            if (tempStr[0].Trim().Trim().Length == 1)
            {
                strDateTime = strDateTime.Insert(0, "0");
            }
            if (tempStr[1].Trim().Trim().Length == 1)
            {
                strDateTime = strDateTime.Insert(3, "0");
            }
            strDateTime = strDateTime.Remove(16, 3);
            try
            {
                formatedDate = DateTime.ParseExact(strDateTime, "dd-MM-yyyy hh:mm tt", null);
            }
            catch (Exception ex)
            {
                throw ex;
                //send wrong fromat date
            }
            return formatedDate;

        }

        public static int GetTotalMonths(DateTime objDate, DateTime subtractDate)
        {
            int totalYear, totalMonth;

            totalYear = objDate.Year - subtractDate.Year;

            if (totalYear < 0)
            {
                throw new Exception("Subtract date is greater than given date range");
                //return -1;
            }
            totalMonth = totalYear * 12;

            totalMonth += (objDate.Month - subtractDate.Month);

            if (totalMonth < 0)
            {
                throw new Exception("Subtract date is greater than given date range");
                // return -1;
            }
            return totalMonth;
        }

        public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public static DateTime ToSqlServerPrecision(DateTime value)
        {
            SqlDateTime sqlValue = new SqlDateTime(value);

            return sqlValue.Value;
        }

        public static DateTime ConvertUnixSeconds(long unixSeconds, long residualNanoseconds)
        {
            DateTime actualDateTime = ConvertUnixSeconds(unixSeconds);

            long ticks = residualNanoseconds / 100;

            return actualDateTime.AddTicks(ticks);
        }

        public static DateTime ConvertUnixSeconds(long unixSeconds)
        {
            return UnixEpoch.AddSeconds(unixSeconds);
        }

        public static string ToFileSortableDateTime(DateTime value)
        {
            return value.ToString("yyyyMMdd'T'HHmmss", CultureInfo.CurrentCulture);
        }

        public static DateTime FromFileSortableDateTime(string value)
        {
            return DateTime.ParseExact(value, "yyyyMMdd'T'HHmmss", CultureInfo.CurrentCulture);
        }

        public static DateTime DDMMYY_MMDDYY(string DDMMYY_Format)
        {

            DateTime convertedDate = DateTime.Parse(DDMMYY_Format.ToString(), new CultureInfo("en-CA", true), DateTimeStyles.NoCurrentDateDefault);
            return convertedDate;
        }
        public static string MMDDYY_DDMMYY(string MMDDYY_Format)
        {

            DateTime convertedDate = DateTime.Parse(MMDDYY_Format);
            return convertedDate.ToString("dd/MM/yyyy");
        }

        #endregion

        public static void MakeReadOnly(Control objcontrol)
        {
            foreach (Control control in objcontrol.Controls)
            {
                if ((control.GetType() == typeof(TextBox)))
                {
                    ((TextBox)control).ReadOnly = true;
                }

                if ((control.GetType() == typeof(DropDownList)))
                {
                    ((DropDownList)control).Enabled = false;
                }

                if ((control.GetType() == typeof(RadioButton)))
                {
                    ((RadioButton)control).Enabled = false;
                }

                if ((control.GetType() == typeof(CheckBox)))
                {
                    ((CheckBox)control).Enabled = false;
                }

                if (control.HasControls())
                {
                    MakeReadOnly(control);
                }
            }
        }

        /// <summary>
        /// This code will help us export to excel
        /// </summary>
        /// <param name="paramTable"></param>
        /// <param name="paramFileName"></param>
        public static void ExportToExcel(DataTable paramTable, string paramFileName)
        {
            GridView objGrid = new GridView();
            objGrid.DataSource = paramTable;
            if (objGrid.Columns.Count > 0)
            {
                objGrid.Columns[0].Visible = false;
            }
            objGrid.DataBind();
            // Excel.Application excel = new Excel.Application();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + paramFileName + ".xls");
            HttpContext.Current.Response.Charset = "";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
            objGrid.RenderControl(htw);
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }


        /// <summary>
        /// This code will help us export to Word Document
        /// </summary>
        /// <param name="dtOld"></param>
        /// <returns></returns>
        public static void ExportToWord(DataTable paramTable, string paramFileName)
        {
            GridView objGrid = new GridView();
            objGrid.DataSource = paramTable;
            if (objGrid.Columns.Count > 0)
            {
                objGrid.Columns[0].Visible = false;
            }
            objGrid.DataBind();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + paramFileName + ".doc");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.ContentType = "application/vnd.word";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            objGrid.RenderControl(htmlWrite);
            HttpContext.Current.Response.Write(stringWrite.ToString());
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// This code will help us export to text file
        /// </summary>
        /// <param name="dtOld"></param>
        /// <returns></returns>
        /// 
        public static void ExportToText(DataTable paramTable, string paramFileName)
        {

        }

        public static DataTable CopyTable(DataRow[] dtOld)
        {
            DataTable dt = new DataTable();
            DataRow drNew;
            if (dtOld.Length > 0)
            {
                foreach (DataColumn dc in dtOld[0].Table.Columns)
                {
                    dt.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
                }
                foreach (DataRow dr in dtOld)
                {

                    drNew = dt.NewRow();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        drNew[i] = dr[i];
                    }
                    dt.Rows.Add(drNew);
                }
            }
            return dt;
        }

        public static DataTable CopyTable(DataTable dtOld)
        {
            DataTable dt = new DataTable();
            DataRow drNew;
            foreach (DataColumn dc in dtOld.Columns)
            {
                dt.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
            }
            foreach (DataRow dr in dtOld.Rows)
            {
                drNew = dt.NewRow();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    drNew[i] = dr[i];
                }
                dt.Rows.Add(drNew);
            }

            return dt;
        }

        public static DataTable GetClone(DataTable dtOld)
        {
            DataTable dt = new DataTable();
            //DataRow drNew;
            foreach (DataColumn dc in dtOld.Columns)
            {
                dt.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
            }
            dt.TableName = dtOld.TableName;
            return dt;
        }

        public static DataTable CreateTable(DataView obDataView)
        {
            if (null == obDataView)
            {
                throw new ArgumentNullException
                ("DataView", "Invalid DataView object specified");
            }

            DataTable obNewDt = obDataView.Table.Clone();
            int idx = 0;
            string[] strColNames = new string[obNewDt.Columns.Count];
            foreach (DataColumn col in obNewDt.Columns)
            {
                strColNames[idx++] = col.ColumnName;
            }

            IEnumerator viewEnumerator = obDataView.GetEnumerator();
            while (viewEnumerator.MoveNext())
            {
                DataRowView drv = (DataRowView)viewEnumerator.Current;
                DataRow dr = obNewDt.NewRow();
                try
                {
                    foreach (string strName in strColNames)
                    {
                        dr[strName] = drv[strName];
                    }
                }
                catch
                {
                    //
                }
                obNewDt.Rows.Add(dr);
            }

            return obNewDt;
        }

        public static SqlDbType ConvertToDbType(Type t)
        {
            Hashtable dbTypeTable = null;
            if (dbTypeTable == null)
            {
                dbTypeTable = new Hashtable();
                dbTypeTable.Add(typeof(System.Boolean), SqlDbType.Bit);
                dbTypeTable.Add(typeof(System.Int16), SqlDbType.SmallInt);
                dbTypeTable.Add(typeof(System.Int32), SqlDbType.Int);
                dbTypeTable.Add(typeof(System.Int64), SqlDbType.BigInt);
                dbTypeTable.Add(typeof(System.Double), SqlDbType.Float);
                dbTypeTable.Add(typeof(System.Decimal), SqlDbType.Decimal);
                dbTypeTable.Add(typeof(System.String), SqlDbType.VarChar);
                dbTypeTable.Add(typeof(System.DateTime), SqlDbType.DateTime);
                dbTypeTable.Add(typeof(System.Byte[]), SqlDbType.VarBinary);
                dbTypeTable.Add(typeof(System.Guid), SqlDbType.UniqueIdentifier);
            }
            SqlDbType dbtype;
            try
            {
                dbtype = (SqlDbType)dbTypeTable[t];
            }
            catch
            {
                dbtype = SqlDbType.Variant;
            }
            return dbtype;
        }

        public static void WriteTextFile(string sIPAddress, string sHostName, string UserId, string url)
        {
            try
            {
                string file_name = ConfigurationManager.AppSettings["TFPath"].ToString();
                //need to r& d for check path on server. 
                //file_name = HttpContext.Current.Server.MapPath(file_name);  
                file_name = file_name + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + ".dll";
                System.IO.StreamWriter objWriter;
                objWriter = new System.IO.StreamWriter(file_name, true);
                objWriter.WriteLine("Date: " + DateTime.Now + " IPAddress: " + sIPAddress + " Computer Name: " + sHostName + " User Id: " + UserId + " Requested Url: " + url);
                objWriter.Close();
            }
            catch
            {
            }
        }

    }


}


